package dao.impl;

import dao.MessageDao;
import model.Company;
import model.Message;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author gzp
 * @create 2022-12-15 11:03
 */
public class MessageDaoImpl implements MessageDao {
    /**
     * The Pstmt.
     */
    PreparedStatement pstmt = null;
    /**
     * The Rs.
     */
    ResultSet rs = null;

    @Override
    public int insert(Message message) {
        int rows = 0;
        String sql = "INSERT INTO message VALUES(null,?,?,?)";
        Connection conn = BaseDao.getConnection();
        try {
            pstmt = conn.prepareStatement(sql);
            pstmt.setLong(1, message.getUid());
            pstmt.setLong(2, message.getSid());
            pstmt.setString(3, message.getDesc());
            rows = pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            BaseDao.close(null, pstmt, conn);
        }
        return rows;
    }


    @Override
    public List<Message> selectBySid(int sid) {
        List<Message> messageList = new ArrayList<Message>();
        String sql = "SELECT * FROM message where sid=?";
        Connection conn = BaseDao.getConnection();
        try {
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, sid);
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                Message message = new Message();
                message.setId(rs.getLong("id"));
                message.setUid(rs.getLong("uid"));
                message.setSid(rs.getLong("sid"));
                message.setDesc(rs.getString("desc"));
                messageList.add(message);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            BaseDao.close(rs, pstmt, conn);
        }
        return messageList;
    }

}
